package com.zlt.appparking.service.impl;

//import com.zlt.appparking.mapper.CouponMapper;
import com.sun.xml.bind.v2.runtime.reflect.Lister;
import com.zlt.appparking.entity.*;
import com.zlt.appparking.mapper.*;
//import com.zlt.appparking.mapper.VipTypeMapper;
import com.zlt.appparking.service.MemberService;
import com.zlt.appparking.utils.SnowFlakeUtil;
import com.zlt.appparking.utils.StringUtil;
import com.zlt.appparking.vo.ActiveUser;
import com.zlt.appparking.vo.CouponVO;
import com.zlt.appparking.vo.ParkingLotVO;
import com.zlt.appparking.vo.VIPVO;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private UserVipMapper userVipMapper;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private VipTypeMapper vipTypeMapper;

    @Autowired
    private ParkingLotMapper parkingLotMapper;

    @Autowired
    private UserWalletMapper userWalletMapper;

    @Autowired
    private VipOrderMapper vipOrderMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public List<VIPVO> selectTime() {
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        if (activeUser == null){
            return null;
        }
        List<VIPVO> vipvos = userVipMapper.selectTime(activeUser.getAuId());
        return vipvos;
    }

    @Override
    public List<CouponVO> coupons() {
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        if (activeUser == null){
            throw new RuntimeException("当前未登录，无法查看已有优惠券");
        }
        //获取用户未使用的优惠券
        List<Coupon> coupons = couponMapper.coupons(activeUser.getAuId(),(byte)0);
        List<CouponVO> couponVOS = new ArrayList<>();
        coupons.forEach( c -> {
            CouponVO couponVO = new CouponVO();
            if (c.getcStatus().equals((byte)0)){//将有效期内的优惠券筛选出来
                BeanUtils.copyProperties(c,couponVO);
                couponVOS.add(couponVO);
            }
        });
        return couponVOS;
    }

    @Override
    public List<CouponVO> overdueCoupons() {
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        if (activeUser == null){
            throw new RuntimeException("当前未登录，无法查看已有优惠券");
        }
        List<Coupon> coupons = couponMapper.overdueCoupons(activeUser.getAuId());//查询已过期或已使用优惠券
        List<CouponVO> couponVOS = new ArrayList<>();
        coupons.forEach( c -> {
            CouponVO couponVO = new CouponVO();
            BeanUtils.copyProperties(c,couponVO);
            couponVOS.add(couponVO);
        });
        return couponVOS;
    }

    @Override
    public List<VIPVO> vipType(Integer id) {
        List<VIPVO> vipvos = new ArrayList<>();
        VipTypeExample vipTypeExample = new VipTypeExample();
        VIPVO vipvo = new VIPVO();
        if (id == null){//查询平台vip
            vipTypeExample.createCriteria().andVtStateEqualTo((byte) 0);
            List<VipType> vipTypes = vipTypeMapper.selectByExample(vipTypeExample);
            VipType vipType = vipTypes.get(0);
            BeanUtils.copyProperties(vipType,vipvo);
            vipvos.add(vipvo);
        } else {//根据停车场id查询对应会员
            vipTypeExample.createCriteria().andPlIdEqualTo(id).andVtStateEqualTo((byte)1);
            List<VipType> vipTypes = vipTypeMapper.selectByExample(vipTypeExample);
            VipType vipType = vipTypes.get(0);
            BeanUtils.copyProperties(vipType,vipvo);
            vipvos.add(vipvo);
        }
        return vipvos;
    }

    @Override
    public List<ParkingLotVO> selectParking(String name) {
        ParkingLotExample example = new ParkingLotExample();
        example.createCriteria().andPlNameLike(name);
        List<ParkingLot> parkingLotList = parkingLotMapper.selectByExample(example);
        List<ParkingLotVO> data = new ArrayList<>();
        for (ParkingLot parkingLot : parkingLotList) {
            ParkingLotVO parkingLotVO = new ParkingLotVO();
            BeanUtils.copyProperties(parkingLot,parkingLotVO);
            data.add(parkingLotVO);
        }
        return data;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public String open(Integer vtId, Integer month, Integer plId,String payType) {
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        if (activeUser == null){
            throw new RuntimeException("当前未登录，请登录后开通");
        }
//        activeUser = new ActiveUser();
//        activeUser.setAuId("1");
        VipTypeExample vipTypeExample = new VipTypeExample();
        //根据会员类型查单价
        if(plId == null){//表示平台会员
            vipTypeExample.createCriteria().andVtStateEqualTo((byte) 0);
        }else {//停车场会员
            vipTypeExample.createCriteria().andVtStateEqualTo((byte) 1).andPlIdEqualTo(plId);
        }
        BigDecimal totalPrice = BigDecimal.valueOf(0);
        List<VipType> vipTypes = vipTypeMapper.selectByExample(vipTypeExample);
        if(vipTypes != null){
            BigDecimal vtPrice = vipTypes.get(0).getVtPrice();//会员单价
            totalPrice = vtPrice.multiply(BigDecimal.valueOf(month));//总价为单价*月份
        }

        if("1".equals(payType)){//钱包支付
            UserWalletExample userWalletExample = new UserWalletExample();
            userWalletExample.createCriteria().andAuIdEqualTo(activeUser.getAuId());
            List<UserWallet> userWalletList = userWalletMapper.selectByExample(userWalletExample);
            if(userWalletList != null){
                UserWallet userWallet = userWalletList.get(0);
                BigDecimal uwMoney = userWallet.getUwMoney();//获取钱包余额
                if(uwMoney.compareTo(totalPrice)>-1){//余额支持扣款
                    //更新钱包
                    userWallet.setUwMoney(uwMoney.subtract(totalPrice));
                    userWalletMapper.updateByPrimaryKeySelective(userWallet);
                    //生成订单
                    long nextId = new SnowFlakeUtil(0).nextId();//生成订单编号 雪花算法
                    VipOrder vipOrder = new VipOrder();
                    vipOrder.setAuId(activeUser.getAuId());//用户
                    vipOrder.setVoNo(nextId+"");//订单号
                    vipOrder.setVoStart(new Date());//开始时间
                    vipOrder.setVoPaytime(new Date());//支付时间
                    vipOrder.setVoState((byte) 1);//支付状态 1-已支付，0-待支付
                    vipOrder.setVtId(vtId);//开通的vip类型
                    //插入数据
                    vipOrderMapper.insertSelective(vipOrder);
                    //查询当前用户是否已是vip
                    UserVip userVip = new UserVip();
                    UserVipExample userVipExample = new UserVipExample();
                    userVipExample.createCriteria().andAuIdEqualTo(activeUser.getAuId()).andVtIdEqualTo(vtId)
                            .andUvStateEqualTo((byte) 0);
                    List<UserVip> userVips = userVipMapper.selectByExample(userVipExample);
                    if(userVips != null  &&  userVips.size()>0){//若该账户已经是会员，则加天数
                        userVip = userVips.get(0);
                        Calendar calendar =Calendar.getInstance();
                        calendar.setTime(userVip.getUvEnd());
                        calendar.add(Calendar.MONTH,month);//在原基础上加会员月份
                        userVip.setUvEnd(calendar.getTime());
                        //更新会员时长
                        userVipMapper.updateByPrimaryKeySelective(userVip);
                    }else{//用户会员已过期
                        userVip.setAuId(activeUser.getAuId());
                        userVip.setUvStart(new Date());
                        Calendar calendar =Calendar.getInstance();
                        calendar.setTime(new Date());
                        calendar.add(Calendar.MONTH,month);
                        userVip.setUvEnd(calendar.getTime());
                        userVip.setVtId(vtId);
                        userVip.setUvState((byte) 0);
                        //插入数据
                        userVipMapper.insertSelective(userVip);
                    }
                    try {
                        //会员到期时间监控
                        redisTemplate.opsForValue().set(activeUser.getAuId()+"_"+plId,userVip.getUvEnd(), StringUtil.dayBetween(new Date(),userVip.getUvEnd()), TimeUnit.DAYS);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                return "true";
            }
        }else if("2".equals(payType)){//微信或支付宝
            //生成订单
            long nextId = new SnowFlakeUtil(0).nextId();//生成订单编号 雪花算法
            VipOrder vipOrder = new VipOrder();
            vipOrder.setAuId(activeUser.getAuId());//用户
            vipOrder.setVoNo(nextId+"");//订单号
            vipOrder.setVoStart(new Date());//开始时间
            vipOrder.setVoPaytime(new Date());//支付时间
            vipOrder.setVoState((byte) 0);//支付状态 1-已支付，0-待支付
            vipOrder.setVtId(vtId);//开通的vip类型
            //将用户开通的vip类型id保存在redis
            redisTemplate.opsForValue().set("uid:vtid" + activeUser.getAuId() ,vtId,30,TimeUnit.MINUTES);
            redisTemplate.opsForValue().set("uid:month" + activeUser.getAuId() ,month,30,TimeUnit.MINUTES);
            //插入数据
            vipOrderMapper.insertSelective(vipOrder);

            //todo 调用支付接口  传订单号，订单金额，订单描述
            String form = "";

            return form;
        }
        return "false";
    }



    @Override
    public List<VIPVO> getDiscount(String pName) {
        return vipTypeMapper.getDiscount(pName);
    }

    @Override
    public boolean change() {
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        if (activeUser == null){
            throw new RuntimeException("当前未登录，请登录后开通");
        }
        //todo 去redis查看开通的vip类型
        //生成用户vip数据
        UserVip userVip = new UserVip();
        UserVipExample userVipExample = new UserVipExample();
        Integer vtId = (Integer) redisTemplate.opsForValue().get("uid:vtid" + activeUser.getAuId());
        //查询停车场
        VipType vipType = vipTypeMapper.selectByPrimaryKey(vtId);
        Integer plId = 0;
        if(vipType != null){
            plId = vipType.getPlId();
        }
        Integer month = (Integer) redisTemplate.opsForValue().get("uid:month" + activeUser.getAuId());
        userVipExample.createCriteria().andAuIdEqualTo(activeUser.getAuId()).andVtIdEqualTo(vtId)
                .andUvStateEqualTo((byte) 0);
        List<UserVip> userVips = userVipMapper.selectByExample(userVipExample);
        if(userVips != null){
            userVip = userVips.get(0);
            Calendar calendar =Calendar.getInstance();
            calendar.setTime(userVip.getUvEnd());
            calendar.add(Calendar.MONTH,month);
            userVip.setUvEnd(calendar.getTime());
            //更新会员时长
            userVipMapper.updateByPrimaryKeySelective(userVip);
        }else{
            userVip.setAuId(activeUser.getAuId());
            userVip.setUvStart(new Date());
            Calendar calendar =Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.MONTH,month);
            userVip.setUvEnd(calendar.getTime());
            userVip.setVtId(vtId);
            userVip.setUvState((byte) 0);
            //插入数据
            userVipMapper.insertSelective(userVip);
        }
        try {
            redisTemplate.opsForValue().set(activeUser.getAuId()+"_"+plId,userVip.getUvEnd(), StringUtil.dayBetween(new Date(),userVip.getUvEnd()), TimeUnit.DAYS);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return true;
    }

}
